import { Ref, watch, computed, WritableComputedRef, ComputedSetter } from 'vue'

export default function useMergedState<T> (
  controlledStateRef: Ref<T | undefined>,
  uncontrolledStateRef: Ref<T>,
  setter?: ComputedSetter<T>
): WritableComputedRef<T> {
  watch(controlledStateRef, value => {
    if (value !== undefined) {
      uncontrolledStateRef.value = value
    }
  })
  return computed({
    get() {
      return controlledStateRef.value === undefined
        ? uncontrolledStateRef.value
        : controlledStateRef.value
    },
    set(v) {
      const oldVal = uncontrolledStateRef.value
      uncontrolledStateRef.value = v
      if (oldVal != v) setter?.(v)
    }
  })
}